package com.mypack.student.controller.student;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.mypack.student.constants.EnumAccountType;
import com.mypack.student.constants.EnumDeleteFlag;
import com.mypack.student.constants.EnumResponse;
import com.mypack.student.context.SessionContext;
import com.mypack.student.dto.account.AccountDTO;
import com.mypack.student.dto.student.StudentDTO;
import com.mypack.student.dto.student.StudentDeleteDTO;
import com.mypack.student.dto.student.StudentExportDTO;
import com.mypack.student.dto.student.StudentSearchDTO;
import com.mypack.student.exception.IdCartNoExistException;
import com.mypack.student.service.account.auth.AccountAuthService;
import com.mypack.student.service.student.StudentService;
import com.mypack.student.utils.Result;
import com.mypack.student.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/student")
@Slf4j
public class StudentController {


    @Autowired
    private StudentService studentService;
    @Autowired
    private AccountAuthService accountAuthService;

    @RequestMapping("/list")
    public Result list(@RequestBody StudentSearchDTO searchDTO) {

        Integer accountType = SessionContext.getCurrentUser().getAccountType();
        if(EnumAccountType.COMMON_USER.getCode().equals(accountType)){
            searchDTO.setDeleteFlag(EnumDeleteFlag.NO.getCode());
        }

        searchDTO.setClazzIdList(accountAuthService.queryClazzIdByAccountId(SessionContext.getAccountId()));

        List<StudentDTO> studentDTOList = studentService.listStudents(searchDTO, true);

        return ResultUtils.success(new PageInfo<>(studentDTOList));


    }

    @RequestMapping("/add")
    public Result add(@RequestBody StudentDTO studentDTO) {

        AccountDTO currentUser = SessionContext.getCurrentUser();

        studentDTO.setCreateUserId(currentUser.getId());

        try {
            studentService.addStudent(studentDTO);
        } catch (IdCartNoExistException e) {
            log.error("身份证号已经存在",e);
            return ResultUtils.fail(e.getEnumResponse());
        }

        return ResultUtils.success();


    }

    @RequestMapping("/update")
    public Result update(@RequestBody StudentDTO studentDTO) {

        if (studentDTO.getId() == null) {
            return ResultUtils.fail(EnumResponse.INVALID_PARAM);
        }

        try {
            studentService.updateStudent(studentDTO);
        } catch (IdCartNoExistException e) {
            return ResultUtils.fail(e.getEnumResponse());
        }

        return ResultUtils.success();


    }

    @RequestMapping("/delete")
    public Result delete(@RequestBody StudentDeleteDTO studentDeleteDTO) {

        if (studentDeleteDTO.getId() == null || StringUtils.isEmpty(studentDeleteDTO.getRemark())) {
            return ResultUtils.fail(EnumResponse.INVALID_PARAM);
        }

        studentDeleteDTO.setDeleteUserId(SessionContext.getAccountId());

        studentService.delete(studentDeleteDTO);

        return ResultUtils.success();

    }

    @GetMapping("/export")
    public void export(StudentSearchDTO searchDTO, HttpServletResponse response) {

        searchDTO.setClazzIdList(accountAuthService.queryClazzIdByAccountId(SessionContext.getAccountId()));

        List<StudentExportDTO> studentExportDTOList = studentService.exportStudents(searchDTO);

        if(CollectionUtils.isEmpty(studentExportDTOList)){
            return;
        }

        Map<String, List<StudentExportDTO>> studentMap = studentExportDTOList.stream().collect(Collectors.groupingBy(StudentExportDTO::getAllClazzName));

        ExcelWriter excelWriter = null;
        try {
            String fileName = URLEncoder.encode("学生信息", "utf-8").replaceAll("\\+", "%20")+".xlsx";
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
            // 这里 指定文件
            excelWriter = EasyExcel.write(response.getOutputStream(),StudentExportDTO.class).build();
            // 升序排序
            List<String> list = Lists.newArrayList(studentMap.keySet()).stream().sorted().collect(Collectors.toList());
            // 降序
//            Collections.sort(list);
            int index = 0;
            for(String allClazzName: list){
                // 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样。StudentExportDTO.class 可以每次都变，我这里为了方便 所以用的同一个class 实际上可以一直变
                WriteSheet writeSheet = EasyExcel.writerSheet(index++, allClazzName).build();
                // 分页去数据库查询数据 这里可以去数据库查询每一页的数据
                List<StudentExportDTO> dataList = studentMap.get(allClazzName);
                excelWriter.write(dataList, writeSheet);
            }
        } catch (Exception e) {
            log.error("导出学生信息异常", e);
        }finally {
            if(excelWriter != null){
                excelWriter.finish();
            }
        }
    }
}
